package com.greate.shiro.springbootshirodemo.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Administrator
 */
public class JwtAuthFilter extends BasicHttpAuthenticationFilter {


	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

		/*判断request的header是否包含token*/
		if (isLoginAttempt(request, response)) {
			try {
				return executeLogin(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		HttpServletRequest request1 = (HttpServletRequest) request;
		System.out.println("URL:" + request1.getRequestURI());
		try {
			request.getRequestDispatcher("/unAuth").forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
		return false;
	}


	/**
	 * 判断 改请求是否进行登录 如果 请求头中有 token 字段 ， 如果有则进行登录
	 *
	 * @param request  请求
	 * @param response 响应
	 * @return 是否包含
	 */
	@Override
	protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
		return ((HttpServletRequest) request).getHeader("token") != null;
	}


	@Override
	protected boolean executeLogin(ServletRequest request, ServletResponse response) {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		String token = httpServletRequest.getHeader("token");
		JwtToken jwtToken = new JwtToken(token);
		// 提交给realm进行登入，如果错误它会抛出异常并被捕获

		try {
			getSubject(request, response).login(jwtToken);
		} catch (AuthenticationException e) {

			e.printStackTrace();
		}
		// 如果没有抛出异常则代表登入成功，返回true
		return true;
	}


}
